package com.my.jli.webapi;

import com.my.jli.Service.ExerciseService;
import com.my.jli.entity.*;
import com.my.jli.util.ExcelUtil;
import com.my.jli.util.JsonUtil;
import com.my.jli.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * @ClassName ExerciseRestController
 * @Description
 * @Author MaYu
 * @Date 2022/4/11 19:18
 * @Version 1.0
 **/
@RestController
@RequestMapping("/webapi/exercise")
public class ExerciseRestController {

    private ExerciseService exerciseService;
    @Autowired
    public void setExerciseService(ExerciseService exerciseService) {
        this.exerciseService = exerciseService;
    }

    @RequestMapping("/list")
    public Map<Exercise, ExerciseOption> getAll(){
        return exerciseService.findAll();
    }

    /**
     * 带查询和分页
     * @param page page
     * @param size size
     * @return 带分页和查询的结果集
     */
    @RequestMapping("/getByPage")
    public PageUtil getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                              @RequestParam(value = "size", defaultValue = "5") Integer size,
                              String title, Integer type, Integer chapter){
        //ding定义排序方式
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Page<Exercise> exercisePage;
        //用于组合习题和选项
        Map<Exercise, ExerciseOption> map = new HashMap<>();

        if ((title == null || Objects.equals(title, "")) && type == null && chapter == null){
            Pageable pageable = PageRequest.of(page, size, sort);
            //先查出所有习题
            exercisePage = exerciseService.findAll(pageable);
            List<Exercise> exerciseList = exercisePage.getContent();

            for (Exercise exercise1 : exerciseList) {
                ExerciseOption option = exerciseService.findOptionByEid(exercise1.getId());
                map.put(exercise1, option);
            }
        } else {
            Pageable pageable = PageRequest.of(page, size, sort);
            Exercise exercise = new Exercise();
            exercise.setTitle(title);
            exercise.setType(type);
            exercise.setChapter(chapter);

            //设置匹配器
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Exercise> example = Example.of(exercise, matcher);

            exercisePage = exerciseService.findAll(example, pageable);
            List<Exercise> exerciseList = exercisePage.getContent();
            for (Exercise exercise1 : exerciseList) {
                ExerciseOption option = exerciseService.findOptionByEid(exercise1.getId());
                map.put(exercise1, option);
            }
        }

        PageUtil pageUtil = new PageUtil(map, exercisePage.getTotalElements(), page);
        pageUtil.setTotalPage(size);
        return pageUtil;
    }

    @RequestMapping("getAllType")
    public List<ExerciseType> getAllType(){
        return exerciseService.findAllType();
    }

    @RequestMapping("/getAllChapter")
    public List<ExerciseChapter> getAllChapter(){
        return exerciseService.findAllChapter();
    }

    /**
     * 添加练习题及其选项
     * @param title 题目
     * @param answer 答案
     * @param type 类型
     * @param chapter 所属章节
     * @param optionA 选项A
     * @param optionB 选项B
     * @param optionC 选项C
     * @param optionD 选项D
     * @return 状态码，1为成功，-1为失败
     */
    @RequestMapping("/saveExercise")
    public int saveExercise(Integer eid, String title, String answer, Integer type, Integer chapter,
                           String optionA, String optionB, String optionC, String optionD){
        if (title == null || answer == null || type == null || chapter == null ||
            optionA == null || optionB == null || optionC == null || optionD == null ||
            title.equals("") || answer.equals("") || optionA.equals("") || optionB.equals("") ||
            optionC.equals("") || optionD.equals("")){

            //以上参数均不能为空
            return -1;
        } else {
            if (eid == null){
                //eid为空则表示是新习题记录
                Exercise exercise = new Exercise();
                exercise.setTitle(title);
                exercise.setAnswer(answer);
                exercise.setType(type);
                exercise.setChapter(chapter);
                //保存习题并返回其主键值
                Integer eId = exerciseService.saveExercise(exercise);

                ExerciseOption option = new ExerciseOption();
                option.setOptionA(optionA);
                option.setOptionB(optionB);
                option.setOptionC(optionC);
                option.setOptionD(optionD);
                //设置上一步获得的习题主键值
                option.setEid(eId);
                //保存选项
                exerciseService.saveExerciseOption(option);

                return 1;
            } else {//否则是更新旧习题信息
                Exercise exercise = exerciseService.findExerciseById(eid);
                exercise.setTitle(title);
                exercise.setAnswer(answer);
                exercise.setType(type);
                exercise.setChapter(chapter);
                exerciseService.saveExercise(exercise);

                ExerciseOption option = exerciseService.findOptionByEid(eid);
                option.setOptionA(optionA);
                option.setOptionB(optionB);
                option.setOptionC(optionC);
                option.setOptionD(optionD);
                exerciseService.saveExerciseOption(option);

                return 1;
            }
        }
    }

    @RequestMapping("/saveExerciseByFile")
    public int saveExerciseByFile(MultipartFile file){
        //记录成功添加的条数
        int count = 0;
        if (file != null && file.getSize() > 0) {//文件不为空
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀
            String[] filename = originalFilename.split("\\.");
            //创建临时文件
            try {
                File tempFile = File.createTempFile(filename[0], "." + filename[1]);
                file.transferTo(tempFile);
                Map<Exercise, ExerciseOption> map = ExcelUtil.getExerciseAndOptionList(tempFile, exerciseService);
                //开始添加
                if (map != null){
                    //System.out.println(map);
                    for (Exercise exercise : map.keySet()) {
                        exerciseService.saveExercise(exercise, map.get(exercise));
                        count++;
                    }
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return count;
    }

    /**
     * 添加章节信息
     * @param chapterName 章节名字
     * @return 状态码，1为成功，0为名字已重复，-1为失败
     */
    @RequestMapping("/addChapter")
    public int addChapter(String chapterName){
        if (chapterName == null || chapterName.equals("")){
            return -1;
        }

        ExerciseChapter chapter = exerciseService.findChapterByName(chapterName);
        if (chapter != null && chapter.getName().equals(chapterName)){
            return 0;
        } else if (chapter == null){
            chapter = new ExerciseChapter();
            chapter.setName(chapterName);
            exerciseService.saveExerciseChapter(chapter);
            return 1;
        } else {
            return -1;
        }
    }

    @RequestMapping("/deleteExercise")
    public int deleteExercise(Integer id){
        exerciseService.deleteExerciseById(id);
        return 1;
    }

    @RequestMapping("/getChapterCompletionRate")
    public double getChapterCompletionRate(Integer cId, Integer sId){
        return exerciseService.getCompletionRate(cId, sId);
    }

    /**
     * 获取某一章节的习题个数
     * @param cId 章节id
     * @return 长度
     */
    @RequestMapping("/getExerciseSizeByCid")
    public int getExerciseSizeByCid(Integer cId){
        List<Exercise> exerciseList = exerciseService.getExerciseByCid(cId);
        return exerciseList.size();
    }

    /**
     * 根据章节id和索引获取习题及其选项
     * @param cId 章节id
     * @param count 索引
     * @return map Exercise=>ExerciseOption
     */
    @RequestMapping("/getExerciseByCid")
    public Map<Exercise, ExerciseOption> getExerciseByCid(Integer cId, @RequestParam(defaultValue = "0") Integer count){
        List<Exercise> exerciseList = exerciseService.getExerciseByCid(cId);
        if (count < exerciseList.size()){
            Exercise exercise = exerciseList.get(count);
            ExerciseOption option = exerciseService.findOptionByEid(exercise.getId());
            Map<Exercise, ExerciseOption> map = new HashMap<>();
            map.put(exercise, option);
            return map;
        } else {
            return null;
        }
    }

    @RequestMapping("/submitAnswer")
    public int submitAnswer(@RequestParam Map<String, String> map, Integer sid){
        int count = 0;
        //System.out.println("map = " + JsonUtil.getAnswerMap(map.get("answerMap")));
        Map<Integer, String> answerMap = JsonUtil.getAnswerMap(map.get("answerMap"));
        if (answerMap != null){
            for (Integer eid : answerMap.keySet()) {//遍历map判断答案是否正确
                String answer = answerMap.get(eid);
                Exercise exercise = exerciseService.findExerciseById(eid);
                if (exercise.getAnswer().equals(answer.trim())){//如果答案正确
                    ExerciseAndStudent es = exerciseService.findESByEidAndSid(eid, sid);
                    if (es == null){
                        es = new ExerciseAndStudent();
                        es.setEid(eid);
                        es.setSid(sid);
                    }
                    es.setDate(new Date());
                    exerciseService.saveExerciseAndStudent(es);
                    count++;
                }
            }
        }
        return count;
    }
    
}
